﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;


namespace WeLinkApi.Common
{ 
    public class SignHelper
    {
        private static Encoding DafaultEncoding = Encoding.UTF8;
        public static string RsaSign(string data, string privateKey)
        {
            byte[] dataInBytes = DafaultEncoding.GetBytes(data);
            return RsaSign(dataInBytes, privateKey);
        }
        public static string RsaSign(byte[] data, string privateKey)
        {
            //加载私钥
            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();

            var pri = RSAKeyConvert.RSAPrivateKeyJava2DotNet(privateKey);
            privateRsa.FromXmlString(pri);
            //privateRsa.FromXmlString(privateKey);
            byte[] signatureBytes = privateRsa.SignData(data, "SHA1");
            return Convert.ToBase64String(signatureBytes);
            
            //转换密钥
            //AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);

            //ISigner signer = SignerUtilities.GetSigner("SHA1WithRSA");
            //signer.Init(true, keyPair.Private);
            //signer.BlockUpdate(data, 0, data.Length);
            //string strBase64 = Convert.ToBase64String(signer.GenerateSignature());
            //return strBase64;


            //IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致     
            
            ////第一个参数为true表示加密，为false表示解密；第二个参数表示密钥
            //c.Init(true, keyPair.Private);

            //byte[] outBytes = c.DoFinal(data);//加密
            //string strBase64 = Convert.ToBase64String(outBytes);
            //return strBase64;
        }
        
        public static string Base64EnCode(string Message)
        {
            byte[] bytes = DafaultEncoding.GetBytes(Message);
            return Convert.ToBase64String(bytes);
        }
        /// <summary>  
        /// Base64解密  
        /// </summary>  
        /// <param name="Message"></param>  
        /// <returns></returns>  
        public static string Base64Decode(string Message)
        {
            byte[] bytes = Convert.FromBase64String(Message);
            return Encoding.Default.GetString(bytes);
        }  


    }

    
}
